package com.ruoyi.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 24466
 * @date 2024/11/17 17:14
 */
@RestController
@RefreshScope
public class SentinelController {

    @SentinelResource(value="info", blockHandler = "infoLimit")
    @GetMapping("/server/config/info")
    public Object info(){
        return "{\"username\":\"admin\",\"password\":\"admin123\"}";
    }

    public static String infoLimit(BlockException exception) {
        return "{\"code:\":\"500\",\"msg\": \"" + "服务流量控制处理\"}" + " : " + exception.getMessage();
    }

    @SentinelResource(value="server-config", blockHandler = "infoLimit")
    @GetMapping("/server/config/info_nacos")
    public Object infoNanos(){
        return "{\"nacos: \n username\":\"admin\",\"password\":\"admin123\"}";
    }

    @SentinelResource(value="slow", fallback = "responseSlow")
    @GetMapping("/server/config/slow")
    public Object slow(){
        int sleepCount = (int) (1 + Math.random() * 1000);
        try {
            Thread.sleep(sleepCount);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "server is here. " + "get Msg from responseSlow!!!: " + sleepCount + "ms";
    }

    public static String responseSlow(Throwable throwable) {
        return "{\"code:\":\"500\",\"msg\": \"" + "服务熔断控制处理： 慢调用\"}" + " : " + throwable.getMessage();
    }
}

